﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	EntityFacade.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System.Diagnostics;

namespace Smart.Common.Entities
{
	/// <summary>
	/// List service facade
	/// </summary>
	[DebuggerStepThrough]
	public abstract class EntityFacade<TEntityType> : IEntityFacade<TEntityType>
		where TEntityType : Entity
	{
		/// <summary>
		/// Facade name
		/// </summary>
		public string Name { get; protected set; }

		/// <summary>
		/// Mapping information
		/// </summary>
		public FacadeMappingInfo MappingInfo { get; set; }

		/// <summary>
		/// Facade list service
		/// </summary>
		public IListService<TEntityType> Service { get; protected set; }

		/// <summary>
		/// List service facade
		/// </summary>
		protected EntityFacade(string name, FacadeMappingInfo mappingInfo, IListService<TEntityType> service)
		{
			Name = name;
			MappingInfo = mappingInfo;
			Service = service;
		}

		/// <summary>
		/// Query list service
		/// </summary>
		public abstract IQueryBuilder<IEntityFacadeQueryExecutor<TEntityType>> Query { get; }

		/// <summary>
		/// Create new entity
		/// </summary>
		public virtual TEntityType Create()
		{
			var list = new EntityList<TEntityType>(Service.Meta, Service);

			return list.Create(typeof(TEntityType));
		}

		/// <summary>
		/// Query and return all items
		/// </summary>
		public virtual IEntityList<TEntityType> All
		{
			get { return Query.Executor.Execute(); }
		}

		/// <summary>
		/// Query and return item by id
		/// </summary>
		public virtual TEntityType GetById(Identifier id)
		{
			var list = new EntityList<TEntityType>(Service.Meta, Service);

			var entity = Service.CreateEntity(typeof(TEntityType), list);

			entity.ID = id;

			return Service.LoadEntity(entity) ? entity : null;
		}
	}
}